package com.hmall.item.web;


import com.hmall.common.dto.FiltersDTO;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.dto.ItemDTO;
import com.hmall.item.pojo.FiltersVO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO getItemList(@RequestParam Integer page
            , @RequestParam Integer size) {


        return itemService.listPage(page, size);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item getItemById(@PathVariable Long id) {

        return itemService.getItemById(id);
    }

    /**
     * 新增商品
     *
     * @param itemDTO
     */
    @PostMapping
    public void insertItem(@RequestBody ItemDTO itemDTO) {

        itemService.insert(itemDTO);
    }

    /**
     * 商品上下架
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        Item itemById = itemService.getItemById(id);
        itemById.setStatus(status);
        itemById.setUpdateTime(new Date());
        itemService.updateById(itemById);
    }

    /**
     * 修改商品
     *
     * @param itemDTO
     */
    @PutMapping
    public void upadateItem(@RequestBody ItemDTO itemDTO) {
        itemService.insertItem(itemDTO);
    }

    /**
     * 删除商品
     *
     * @param id
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        itemService.removeById(id);
    }
    @GetMapping("/category")
    public FiltersVO getFilter(@RequestParam("category") String category){
        FiltersVO filtersVO = itemService.selrct(category);
        List<String> collect = filtersVO.getBrand().stream().distinct().collect(Collectors.toList());
        filtersVO.setBrand(collect);
        return filtersVO;
    }

    @GetMapping("/categorys")
    public PageDTO<Item> list1(@RequestBody FiltersDTO filtersDTO){
        return itemService.pagelist(filtersDTO);

    }

    @PutMapping("/stock/{itemId}/{num}")
    public void  updateStock(@PathVariable Long itemId,@PathVariable Integer num){
      if(itemService.getById(itemId).getStock()<0){
          throw new RuntimeException("库存为0");
      }

        itemService.stock(itemId,num);

    }

    @GetMapping("/getCategory")
    public List<String> getlist(){

        return itemService.getCategoryList();

    }

    @GetMapping("/getBrand")
    public List<String> getBrandList(){

        return itemService.getBrandList();

    }
}


